package com.itmck.util;


import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/8/20 14:16
 **/

public class RequestUtil {

    public static String getRequestValueByKey(HttpServletRequest request, String key) {

        Map<String, Object> requestParamsMap = RequestUtil.getRequestParamsMap(request);
        Map.Entry<String, Object> obj = requestParamsMap.entrySet()
                .stream()
                .filter(e -> e.getKey().equals(key))
                .findFirst()
                .orElse(null);
        if (null != obj) {
            return (String) obj.getValue();
        }
        return null;
    }

    public static Map<String, Object> getRequestParamsMap(HttpServletRequest request) {

        HashMap<String, Object> emptyMap = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameter = parameterNames.nextElement();
            if (!StringUtils.isEmpty(parameter)) {
                String value = request.getParameter(parameter);
                if (!StringUtils.isEmpty(parameter)) {
                    emptyMap.put(parameter, value);
                }
            }
        }
        return emptyMap;
    }

}